//封装aip请求信息
import axios from 'axios'
//js文件中需要单独引用，将请求进行封装，封装响应，用于消息提示
import { Message } from 'element-ui';
import router from "../router";

/**
 * 自定义响应拦截器
 */
axios.interceptors.response.use(success => {
    //success.status  状态码存在
    //success.status == 200 :HTTP服务器访问接口200的status
    //success.data.status == 500 :返回jason的status

    //业务上的错误
    if(success.status && success.status == 200 && success.data.status == 500) {
        //将服务端写出来的RespBean的message给展示出来
        Message.error({message:success.data.msg})
        return;
    }
    if (success.data.msg) {
        Message.success({message:success.data.msg})
    }
    return success.data;
},error => {
    //失败
    if(error.response.status == 504 || error.response.status == 404) {
        Message.error({message:'服务器被吃了····'})
    } else if(error.response.status == 403) {
        Message.error({message:'权限不足，请联管理员！'})
    } else if(error.response.status == 401) {
        Message.error({message:'尚未登录，请登录！'})
        //返回登录页
        router.replace("/");
    } else {
        if(error.response.data.msg) {
            //返回服务端的错误信息
            Message.error({message:error.response.data.msg})
        } else {
            Message.error({message:'未知错误！'})
        }
    }
    return;
})

//post请求封装
//定义一个全局变量，防止后期需要添加前缀
let base = '';
//登录请求默认只支持key-value的形式传递参数
export const postKeyValueRequest=(url,params)=>{
    //类似于ajax
    return axios({
        method:'post',
        url:`${base}${url}`,
        data:params,
        transformRequest:[function (data) {
            let ret = '';
            for(let i in data) {
                ret += encodeURIComponent(i) + '=' + encodeURIComponent(data[i]) + '&'
            }
            console.log(ret);
            return ret;
        }],
        headers:{
            'Content-Type':'application/x-www-form-urlencoded'
        }
    });
}

//传递jsaon的请求封装
export const postRequest=(url,params)=>{
    return axios({
        method: 'post',
        url:`${base}${url}`,
        data:params
    })
}
export const putRequest=(url,params)=>{
    return axios({
        method: 'put',
        url:`${base}${url}`,
        data:params
    })
}
export const getRequest=(url,params)=>{
    return axios({
        method: 'get',
        url:`${base}${url}`,
        data:params
    })
}
export const deleteRequest=(url,params)=>{
    return axios({
        method: 'delete',
        url:`${base}${url}`,
        data:params
    })
}